<template>
  <div class="app-container">
    <div class="container-bg">
      <el-row :gutter="12">
        <el-col :span="16">
          <el-form ref="upForm" :model="form"
            size="medium" label-width="0px">
            <el-col :span="14">
              <div class="tab-line colorBlue">
                <div>应用和插件升级</div>
              </div>
            </el-col>
            <br>
            <el-col :span="12">
              <form id="uploaForm" class="layui-btn">
                <div class="rel"></div>
                <input type="file" name="fileTrans" ref="upFile" id="upFile" />
                <input type="hidden" name="file" />
              </form>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                <!-- <el-button type="primary" ref="upBtn" @click="upDataBtn" :disabled="isNoFile"> -->
                <el-button type="primary" ref="upBtn" id="upDataBtn">
                  更新
                </el-button>
              </el-form-item>
            </el-col>
          </el-form>
          <el-form ref="elForm" :model="form" size="medium" label-width="150px" v-if="false">
            <el-col :span="13">
              <div class="tab-line">
                <div>软件升级</div>
              </div>
            </el-col>

            <el-col :span="13">
              <el-form-item>
                <Upload
                  :config="software"
                  @init="init"
                  @handleUpload="handleUploadSoftware"
                ></Upload>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="是否保留配置文件">
                <el-switch
                  v-model="form.isSoftwareSaveConfig"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item>
                <el-button type="primary" @click="softwareUpgrade" :disabled="isSoftWareDisable">
                  3.更新
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <div class="tab-line">
                <div>算法更新</div>
              </div>
            </el-col>
            <el-col :span="13">
              <el-form-item label="是否保留配置文件">
                <el-switch
                  v-model="form.isAlgorithmSaveConfig"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item>
                <Upload
                  :config="algorithm"
                  @init="init"
                  @handleUpload="handleUploadAlgorithm"
                ></Upload>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item>
                <el-button type="primary" @click="algorithmUpgrade" :disabled="isAlgorithmDisable"
                >3.更新
                </el-button
                >
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <div class="tab-line">
                <div>固件更新</div>
              </div>
            </el-col>
            <el-col :span="13">
              <el-form-item>
                <Upload
                  :config="firmware"
                  @init="init"
                  @handleUpload="handleUploadFirmware"
                ></Upload>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="是否保留配置文件">
                <el-switch
                  v-model="form.isFirmwareSaveConfig"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item>
                <el-button type="primary" :disabled="isFirmWareDisable" @click="firmwareUpgrade"
                >3.更新
                </el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-col>
        <el-col :span="12" v-if="false">
          <el-col :span="12" class="right-progress">
            <div class="tab-line">
              <div>相关信息</div>
            </div>
            <el-timeline :reverse="true">
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                :timestamp="activity.timestamp">
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </el-col>
        </el-col>
      </el-row>
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%">
        <span>文件正在上传中，这可能花费数分钟，请耐心等待</span>
      </el-dialog>
      <div class="barbox layui-hide">
        <p class="barTxt"></p>
        <div class="bar"></div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  firmwareUpgradeApi,
  firmwareUpgradeInitApi,
  softwareUpgradeApi,
  softwareUpgradeInitApi,
  algorithmUpgradeApi,
  algorithmUpgradeInitApi,
  uploadSoftwareApi,
  mergeSoftwareApi,
  checkSoftwareApi,
  uploadAlgorithmApi,
  mergeAlgorithmeApi,
  checkAlgorithmApi,
  uploadFirmwareApi,
  mergeFirmwareApi,
  checkFirmwareApi, getBackendInfo,
} from "@/api/access/equipment";
import SparkMD5 from "spark-md5";
import Cookies from "js-cookie";
import Upload from "./components/Upload.vue";
import $ from 'jquery'
import { Loading } from 'element-ui'
let loading;

export default {
  components: {
    Upload,
  },
  data() {
    return {
      progressInterval: null,
      activities: [{
        content: '完成第三步更新步骤后，时间线将自动显示',
        timestamp: '该时间线内包含详细的更新信息'
      },],

      loading: false,
      dialogVisible: false,
      isNoFile: true,
      isSoftWareDisable: true,
      isAlgorithmDisable: true,
      isFirmWareDisable: true,
      form: {
        isFirmwareSaveConfig: 1,
        isSoftwareSaveConfig: 1,
        isAlgorithmSaveConfig: 1,
      },
      fileList: [],
      software: {
        uploadUrl: "/cgi-bin/entry.cgi/system/software-upgrade?sliceId=",
        mergeUrl: "/cgi-bin/entry.cgi/system/software-upgrade?merge=",
        checkUrl: "/cgi-bin/entry.cgi/system/software-upgrade?check=",
        type: "software",
      },
      firmware: {
        uploadUrl: "/cgi-bin/entry.cgi/system/firmware-upgrade?sliceId=",
        mergeUrl: "/cgi-bin/entry.cgi/system/firmware-upgrade?merge=",
        checkUrl: "/cgi-bin/entry.cgi/system/firmware-upgrade?check=",
        type: "firmware",
      },
      algorithm: {
        uploadUrl: "/cgi-bin/entry.cgi/system/algorithm-upgrade?sliceId=",
        mergeUrl: "/cgi-bin/entry.cgi/system/algorithm-upgrade?merge=",
        checkUrl: "/cgi-bin/entry.cgi/system/algorithm-upgrade?check=",
        type: "algorithm",
      },
    };
  },
  created() {
    // this.getUpdateInfo()
  },
  methods: {
    getUpdateInfo() {
      this.progressInterval = setInterval(() => {
        getBackendInfo().then(res => {
          // console.log('进度', res);
          this.activities = [{
            content: '完成第三步更新步骤后，时间线将自动显示',
            timestamp: '该时间线内包含详细的更新信息'
          },]
          res.process.map((c, i) => {
            console.log('c', c)
            this.activities.push({
              content: c.progressDetail,
              timestamp: c.progressDate
            })

          })
        })
      }, 2000)
    },
    firmwareUpgrade() {
      firmwareUpgradeApi(this.form.isFirmwareSaveConfig).then((res) => {
        console.log(res);
        this.$message.success("更新成功");
        this.getUpdateInfo()
      });
    },
    softwareUpgrade() {
      softwareUpgradeApi(this.form.isSoftwareSaveConfig).then((res) => {
        this.$message.success("更新成功");
        this.getUpdateInfo()
      });
    },
    algorithmUpgrade() {
      algorithmUpgradeApi(this.form.isAlgorithmSaveConfig).then((res) => {
        this.$message.success("更新成功");
        this.getUpdateInfo()
      });
    },
    init(type) {
      // console.log(type);
      switch (type) {
        case "firmware":
          firmwareUpgradeInitApi().then((res) => {
            this.$message.success("初始化成功");
          });
          break;
        case "software":
          softwareUpgradeInitApi().then((res) => {
            this.$message.success("初始化成功");
          });
          break;
        case "algorithm":
          algorithmUpgradeInitApi().then((res) => {
            this.$message.success("初始化成功");
          });
          break;
        default:
          break;
      }
    },
    // 上传软件
    handleUploadSoftware([file, md5]) {
      console.log(file)
      if(file){
        this.dialogVisible = true
      }

      // 创建切片
      let size = 1024 * 1024 * 10; //10MB 切片大小
      let fileChunks = [];
      let index = 0; //切片序号

      for (let cur = 0; cur < file.size; cur += size) {
        fileChunks.push({
          hash: index++,
          chunk: file.raw.slice(cur, cur + size),
        });
      }
      // 上传切片
      const uploadList = [];
      fileChunks.map((item, index) => {
        const fn = async () => {
          return uploadSoftwareApi(item.hash, item.chunk).then((res) => {
            // console.log(res);
          });
        };
        uploadList.push(fn);
      });

      let i = 0; //记录发送的请求个数

      const send = async () => {
        if (i >= uploadList.length) {
          mergeSoftwareApi(fileChunks.length).then((res) => {
            // console.log(res);
            checkSoftwareApi(md5).then((res) => {
              // console.log(res);
              this.$message.success("上传成功");
              this.dialogVisible = false
            });
          });

          return;
        }
        await uploadList[i]();
        i++;
        send();
      };
      send();
      this.isSoftWareDisable = false
    },
    // 上传算法
    handleUploadAlgorithm([file, md5]) {
      if(file){
        this.dialogVisible = true
      }

      // 创建切片
      let size = 1024 * 1024 * 10; //10MB 切片大小
      let fileChunks = [];
      let index = 0; //切片序号

      for (let cur = 0; cur < file.size; cur += size) {
        fileChunks.push({
          hash: index++,
          chunk: file.raw.slice(cur, cur + size),
        });
      }
      // 上传切片
      const uploadList = [];
      fileChunks.map((item, index) => {
        const fn = async () => {
          return uploadAlgorithmApi(item.hash, item.chunk).then((res) => {
            // console.log(res);
          });
        };
        uploadList.push(fn);
      });

      let i = 0; //记录发送的请求个数

      const send = async () => {
        if (i >= uploadList.length) {
          mergeAlgorithmeApi(fileChunks.length).then((res) => {
            // console.log(res);
            checkAlgorithmApi(md5).then((res) => {
              // console.log(res);
              this.$message.success("上传成功");
              this.dialogVisible = false

            });
          });

          return;
        }
        await uploadList[i]();
        i++;
        send();
      };
      send();
      this.isAlgorithmDisable = false
    },
    //上传硬件
    handleUploadFirmware([file, md5]) {
      if(file){
        this.dialogVisible = true
      }
      // 创建切片
      let size = 1024 * 1024 * 10; //10MB 切片大小
      let fileChunks = [];
      let index = 0; //切片序号

      for (let cur = 0; cur < file.size; cur += size) {
        fileChunks.push({
          hash: index++,
          chunk: file.raw.slice(cur, cur + size),
        });
      }
      // 上传切片
      const uploadList = [];
      fileChunks.map((item, index) => {
        const fn = async () => {
          return uploadFirmwareApi(item.hash, item.chunk).then((res) => {
            // console.log(res);
          });
        };
        uploadList.push(fn);
      });

      let i = 0; //记录发送的请求个数

      const send = async () => {
        if (i >= uploadList.length) {
          mergeFirmwareApi(fileChunks.length).then((res) => {
            // console.log(res);
            checkFirmwareApi(md5).then((res) => {
              // console.log(res);
              this.$message.success("上传成功");
              this.dialogVisible = false

            });
          });
          return;
        }
        await uploadList[i]();
        i++;
        send();
      };
      send();
      this.isFirmWareDisable = false
    },
  },
  mounted() {
    let loadingInstance;
    let that = this;

    $('#uploaForm .rel').click(function () {
      $('#upFile').click();
    })

    $('#upFile').change(function () {
      var file = document.getElementById('upFile').files[0];
      var oFReader = new FileReader();
      oFReader.readAsDataURL(file);
      oFReader.onloadend = function (oFRevent) {      
        var src = oFRevent.target.result;
        console.log(450, src);
      }     
    })

    $('#upDataBtn').click(function () {
      var files = $('#upFile').prop('files');
      console.log(files);
      console.log(typeof files);
      if (files.length == 0) {
        alert('请选择文件');
        return;
      }
      if (files[0].name.indexOf('.bin') == -1) {
        alert('只能使用.bin文件');
        return;
      }

      startLoading();
      var sIP = window.location.host;
      if (sIP.indexOf(':') > -1) {
        sIP = sIP.substring(0, sIP.indexOf(':'));
      }

      var xhr = createXHR();
        // xhr.open('get', "upgrade/reset?_time="+new Date().getTime());
        xhr.open('get', "http://" + sIP + "/upgrade/reset?_time="+new Date().getTime());
        xhr.onreadystatechange=function(){
            // readyState == 4说明请求已完成
            if(xhr.readyState==4){
              if(xhr.status==200 || xhr.status==304){
                  // 结果在控制台查看
                  console.log('reset' + ' ' + JSON.parse(xhr.response).status);
                  if (JSON.parse(xhr.response).status == 0) {
                    // callback(xhr.responseText);
                  } else {
                    that.$message.error("重置进度失败");
                    endLoading();
                    return false;
                  }
                }
            }
        }
        xhr.send();

        setTimeout(function () {
          $('.barbox .bar').css('width', 0);
          $('.barbox .barTxt').text(0);
          $('.barbox').removeClass('layui-hide');

          // 上传文件
          var xhr2 = createXHR();
          // xhr2.open('post', "http://" + sIP + "/upgrade", true);
          xhr2.open('post', "http://" + sIP + "/upgrade?filename="+files[0].name, true);
          xhr2.send(files[0]);
          xhr2.onload = function () {
              console.log('upload' + ' ' + xhr2.statusText);
          }
          xhr2.onerror = function () {
              console.log('upload' + ' err ' + xhr2.statusText);
          }
          var pace = 0;
          // 获取进度
          var keepGet = setInterval(function () {
              var xhr3 = createXHR();
              // xhr3.open('get', "http://" + sIP + "/upgrade?_time="+new Date().getTime());
              xhr3.open('get', "http://" + sIP + "/upgrade/progress?_time="+new Date().getTime());
              xhr3.onreadystatechange=function(){
                // readyState == 4说明请求已完成
                if(xhr3.readyState==4){
                  if(xhr3.status==200 || xhr3.status==304){
                    // 结果在控制台查看
                    var dataJson = JSON.parse(xhr3.response);
                    if (dataJson.progress > 0) {
                      pace = dataJson.progress;
                    }
                    console.log(531, pace);
                    $('.barbox .bar').css('width', pace+'%');
                    $('.barbox .barTxt').text(pace+'%');
                    
                    if (pace >= 100) {
                      clearInterval(keepGet);
                      that.$message.success("上传成功");

                      var sucNum = 0;
                      var keepGetStatu = setInterval(function () {
                        var xhr4 = createXHR();
                        // xhr4.open('get', "http://" + sIP + "/upgrade?_time="+new Date().getTime());
                        xhr4.open('get', "http://" + sIP + "/upgrade/status?_time="+new Date().getTime());
                        xhr4.onreadystatechange=function(){
                          console.log(536, xhr4);
                          if(xhr4.readyState==4){
                            if(xhr4.status==200 || xhr4.status==304){
                              var dataJson = JSON.parse(xhr4.response);
                              console.log(547, dataJson);
                              if (dataJson.status < 0) {
                                clearInterval(keepGetStatu);
                                endLoading();
                                $('.barbox .bar').css('width', 0);
                                $('.barbox .barTxt').text(0);
                                $('.barbox').removeClass('layui-hide');
                                if (dataJson.status == -100) {
                                  that.$message.error("有一个正在升级中");
                                } else if (dataJson.status == -101) {
                                  that.$message.error("system 执行失败");
                                } else if (dataJson.status == -102) {
                                  that.$message.error("打开文件失败");
                                } else if (dataJson.status == -103) {
                                  that.$message.error("升级包校验失败");
                                } else if (dataJson.status == -104) {
                                  that.$message.error("升级包解压失败");
                                } else if (dataJson.status == -105) {
                                  that.$message.error("未知的升级包类型");
                                } else if (dataJson.status == -106) {
                                  that.$message.error("接受升级包失败");
                                } else if (dataJson.status == -107) {
                                  that.$message.error("下载升级包失败");
                                } else if (dataJson.status == -999) {
                                  that.$message.error("不支持的方法");
                                }
                              } else {
                                if (dataJson.status == 0) {
                                  clearInterval(keepGetStatu);
                                  loading.setText('升级成功');
                                  setTimeout(() => {
                                    endLoading();
                                    $('.barbox .bar').css('width', 0);
                                    $('.barbox .barTxt').text(0);
                                    $('.barbox').addClass('layui-hide');
                                    if(files[0].name.indexOf('FaceTerminal_V') != -1 || files[0].name.indexOf('MVNT-8630_V') != -1){
                                      that.$store.dispatch("LogOut").then(() => {
                                        location.href = "/index";
                                      });
                                    }
                                    if(files[0].name.indexOf('libplugins_wanrui-V') != -1 || files[0].name.indexOf('plugins-aiot-V') != -1 || files[0].name.indexOf('plugins-vrui-V') != -1){
                                      that.$router.push('/network-config')
                                    }
                                  }, 5000);
                                } else if (dataJson.status == 1) {
                                  loading.setText('正在接受文件');
                                } else if (dataJson.status == 2) {
                                  loading.setText('正在校验文件');
                                } else if (dataJson.status == 3) {
                                  loading.setText('校验完成');
                                } else if (dataJson.status == 4) {
                                  sucNum++;
                                  loading.setText(sucNum >= 8 ? '正在安装，安装完成后将自动重启，请耐心等待！' : '正在解压文件');
                                } else if (dataJson.status == 5) {
                                  loading.setText('升级包解压完成');
                                } else if (dataJson.status == 6) {
                                  loading.setText('正在安装');
                                }
                              }
                            }
                          }
                        }
                        xhr4.send();
                      }, 3000)
                    }
                  }
                }
              }
              xhr3.send();
          }, 500)
        }, 100)
    })

    function createXHR() {
      if (typeof XMLHttpRequest != "undefined") {
          return new XMLHttpRequest();
      }
      if (typeof ActiveXobject == "undefined") {
          throw new Error(" not support ");
      }
      //判断是否为 IE
      if (typeof arguments.callee.activeString != "string") {
          var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp3.0", "MSXML2.XMLHttp"],
              i, len;
          for (var i = 0; i < versions.length; i++) {
              try {
                  new ActiveXobject(versions[i]);
                  arguments.callee.activeString = versions[i];
                  break;
              } catch (ex) {
                  //  no action
              }
          };
      }
      return new ActiveXobject(arguments.callee.activeString);
    }

    function startLoading() {
      loading= Loading.service({
        lock:true,
        text:"正在上传文件",
        background:'rgba(0,0,0,0.3)',
      })
    }

    function endLoading() {
      loading.close();
    }
  },
  watch: {},
  // destroyed() {
  //   clearInterval(this.progressInterval)
  // },
};
</script>

<style lang="scss" scoped>
.container-bg .colorBlue {
  background-color: #C6E2FF;
}
#uploaForm {
  background-color: #E4E7ED;
}
#upFile {
  color: #000;
}
.tab-line {
  height: 40px;
  display: flex;
  justify-content: space-between;
  background-color: #f9f9f9;
  align-items: center;
  padding: 0 20px;
  margin-bottom: 10px;
}

.right-progress {
  height: 600px;
  overflow-y: scroll;


}
//::-webkit-scrollbar {
//  display: none; /* Chrome Safari */
//}
html::-webkit-scrollbar {
  width: 20px;
}

html::-webkit-scrollbar-track {
  background-color: black;
}

html::-webkit-scrollbar-thumb {
  background: #4e4e4e;
  border-radius: 25px;
}

.barbox {
  width: 30%;
  height: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin: 22% 28.5%;
  overflow: hidden;
  position: relative;
  z-index: 2001;
}

.barbox .bar {
  width: 0px;
  height: 20px;
  background: #4473C5;
  color: #fff;
  text-align: center;
  font-family: Tahoma;
  font-size: 18px;
  line-height: 30px;
  opacity: 0.5;
  position: absolute;
}

.barbox .barTxt {
  color: #fff;
  position: absolute;
  top: 0;
  left: 45%;
  z-index: 100;
}

#upDataBtn {
  padding: 11px 20px;
}

#uploaForm {
  position: relative;
}

#uploaForm,
#upFile {
  width: 100%;
  cursor: pointer;
}

#uploaForm .rel {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}

#upFile input:hover {
  cursor: pointer;
}
</style>
